import axios from "axios";
import { setUserStore } from "@/stores/user";
import pinia from "@/stores";
import { ElMessage } from "element-plus";

const server = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 3000,
  headers: {},
});
server.interceptors.request.use(
  (config) => {
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);
server.interceptors.request.use(
  function (config) {
    // config.headers.token = store.state.user.token;
    const userStore = setUserStore(pinia);

    // @ts-ignore
    config.headers.token = userStore.token;
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);
server.interceptors.response.use(
  (response) => {
    if (response.data.code === 20000 || response.data.code === 200) {
      return response.data.data;
    } else {
      ElMessage.error(response.data.message);
      return Promise.reject(response.data);
    }
  },
  (err) => {
    ElMessage.error("请求错误");
    return Promise.reject(err);
  }
);
export default server;
